package com.tangding.net.pool;

import java.util.Collection;
import java.util.Map;
import java.util.Set;

import javax.annotation.PostConstruct;

import com.tangding.common.logx.LogHelp;
import com.tangding.common.utils.JacksonUtil;
import com.tangding.net.handler.MessageRes;

import io.netty.channel.Channel;

public abstract class BaseNettySessionPool {

	Map<Channel, String> pool = null;
	
//	@Autowired
//	EventBusPool eventBusPool;
	
	@PostConstruct
	protected abstract void init();
	
	public Collection<String> onlines(){
		return pool.values();
	}
	
	public boolean online(String uid) {
		return pool.containsKey(uid);
	}
	
	public void addSession(Channel c, String uid) {
		pool.put(c, uid);
		LogHelp.doLogApp("add channel;online count:" + pool.size());
	}
	
	public void dropSession(Channel c) {
		String uid = getUid(c);
		try {
			c.close();
			remove(c);
		} catch (Exception e) {
			LogHelp.doLogException(e);
		} finally {
			LogHelp.doLogApp("drop [" + uid + "] channel;online count:" + pool.size());
		}
//		eventBusPool.remove(getUid(c));
	}
	
	public Channel dropSession(String uid) {
		Channel c = getChannel(uid);
//		eventBusPool.remove(uid);
		if (c != null) {
			dropSession(c);
			return c;
		}
		return null;
	}
	
	public Set<Channel> getChannels() {
		return pool.keySet();
	}
	
	public abstract Channel getChannel(String uid);
	
	public String getUid(Channel c) {
		String uid = pool.get(c);
		return uid;
	}
	
	public void clear() {
		pool.clear();
	}

	protected String remove(String uid) {
		return pool.remove(getChannel(uid));
	}
	
	protected String remove(Channel channel) {
		return pool.remove(channel);
	}
	
	public void doResponse(String uid, String cmd, Object data){
		Channel channel = getChannel(uid);
		if (channel != null && channel.isActive()) {
			MessageRes response = new MessageRes();
			response.setCmd(cmd);
			response.setData(data);
//			System.out.println(JacksonUtil.toJson(response));
			channel.writeAndFlush(JacksonUtil.toJson(response).getBytes());
		}
	}
}